<template>
  <!-- 企业注册 -->
  <div class="register-wrap">
    <registerDialog v-show="active === 1" ref="registerDialog" />
    <section v-show="active !== 1" class="enterprise-info">
      <div class="dialog">
        <h3>完善公司信息</h3>
        <el-steps :active="active" align-center>
          <el-step title="账号密码" />
          <el-step title="基本信息" />
          <el-step title="经营范围" />
        </el-steps>
        <div v-show="active === 2">
          <div class="form-person">
            <el-form ref="baseInfo" :rules="baseRules" :model="formData" label-width="80px">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item prop="name" label="企业名称">
                    <el-input v-model="formData.name" placeholder="请输入企业名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="sysEnterpriseType" label="企业类型">
                    <el-select v-model="formData.sysEnterpriseType" style="width: 100%;" placeholder="请选择企业类型" @change="checkCompanyType($event)">
                      <el-option
                        v-for="item in supperType"
                        :key="item.id"
                        :label="item.typeName"
                        :value="item.typeNum"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="creditCodePic" label="信用代码">
                    <el-input v-model="formData.creditCodePic " placeholder="请输入社会统一信用代码" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="legalperson" label="单位法人">
                    <el-input v-model="formData.legalperson" placeholder="请输入单位法人" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="企业性质" prop="nature">
                    <el-select v-model="formData.nature" style="width:100%" size="medium">
                      <el-option
                        v-for="dict in natureData"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="所在区域" prop="province">
                    <el-cascader v-model="formData.currentProvince" placeholder="请选择所在区域" :props="cityNormalizer" :options="cityOptions" clearable style="width: 100%" @change="changeCitySelect">
                      <template slot-scope="{ data }">
                        <span>{{ data.label }}</span>
                      </template>
                    </el-cascader>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="address" label="详细地址">
                    <el-input v-model="formData.address" placeholder="请输入企业详细地址" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="" prop="isCheck">
                    <template slot="label">
                      <span class="labelTitle">审核方式</span>
                    </template>
                    <el-select v-model="formData.isCheck" style="width:100%" clearable placeholder="请选择审核方式">
                      <el-option
                        v-for="item in isCheckList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="成立日期" prop="establishmentTime">
                    <el-date-picker
                      v-model="formData.establishmentTime"
                      value-format="yyyy-MM-dd"
                      style="width:100%"
                      type="date"
                      placeholder=""
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="营业执照" prop="unitCreditCodePicUrl">
                    <ImgUploadOne
                      ref="fileUplode"
                      @getFilePic="getBusinessPic"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-form :inline="true" :model="formData" :rules="baseRules" label-width="110px">
              <el-row :gutter="10">
                <el-col :span="12" class="certificate-wrap">
                  <div v-if="checkSupperType === '03' || checkSupperType === '04'" class="certi-item">
                    <h3 class="certi-titile">资质证书</h3>
                    <el-row>
                      <el-col :span="8">
                        <div class="upload">
                          <ImgUploadOne :edit-file-list="certifileList" @getFilePic="getCertifileList" />
                        </div>
                      </el-col>
                      <el-col :span="16">
                        <el-form-item prop="certificateNum" label="证书编号">
                          <el-input v-model="formData.certificateNum" size="small" placeholder="请输入证书编号" />
                        </el-form-item>
                        <el-form-item prop="validUntil" label="">
                          <label slot="label" v-html="`有&ensp;效&ensp;期`" />
                          <el-date-picker v-model="formData.validUntil" value-format="yyyy-MM-dd" style="width:185px;" size="small" type="date" placeholder="请选择证书资质有效期" />
                        </el-form-item>
                        <el-form-item prop="qualificationLevel" label="资质等级">
                          <el-select v-model="formData.qualificationLevel" size="small" clearable style="width:185px;" placeholder="请选择资质等级">
                            <el-option
                              v-for="item in proGrade"
                              :key="item.dictValue"
                              :label="item.dictLabel"
                              :value="item.dictValue"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                </el-col>
                <el-col v-for="cert in certificateJson" :key="cert.id" :span="12" class="certificate-wrap">
                  <div class="certi-item">
                    <h3 class="certi-titile">{{ cert.certificateName }}</h3>
                    <el-row>
                      <el-col :span="8">
                        <div class="upload">
                          <ImgUploadOneC
                            :cert-id="certId"
                            :edit-file-list="cert.appFiles"
                            @getCertData="getCertData"
                            @click.native="handleId(cert.id)"
                            @getFilePic="cert.appFilePic = $event"
                          />
                        </div>
                      </el-col>
                      <el-col :span="16">
                        <el-form-item v-for="item in cert.detailList" :key="item.id" :label="item.fieldName" prop="">
                          <el-input v-model="item.value" placeholder="" size="small" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div class="btn-wrap">
            <el-button size="medium" type="primary" @click="active = 1">上一步</el-button>
            <!-- <el-button v-if="formData.tempId === null" size="medium" type="primary" @click="goRegister">注册</el-button> -->
            <el-button size="medium" type="primary" @click="goBusiness">下一步</el-button>
          </div>
        </div>
        <div v-show="active === 3" v-loading="loading" class="form-person">
          <el-form :model="businessData">
            <div class="certificate-wrap">
              <div v-for="(item,index) in titleList" :key="index" class="certi-item">
                <h3 class="certi-titile">{{ item.businessName }}</h3>
                <el-row>
                  <el-checkbox-group v-if="item.children.length > 0" v-model="CheckBusinessData[index]" @change="handleChange(item)">
                    <el-checkbox v-for="(i,ind) in item.children" :key="ind" :label="i.id">{{ i.businessName }}</el-checkbox>
                  </el-checkbox-group>
                  <div v-else class="no-data">
                    <p><svg-icon icon-class="no-data" class="no-data-icon" /></p>
                    <p>暂无数据</p>
                  </div>
                </el-row>
              </div>
            </div>
          </el-form>
          <div class="btn-wrap">
            <el-button size="medium" type="primary" @click="active = 2">上一步</el-button>
            <el-button size="medium" type="primary" @click="goRegister">注册</el-button>
          </div>
        </div>
      </div>
    </section>

  </div>
</template>

<script>
/** 页面组件 start*/
// 页面组件- 附件上传
import ImgUploadOneC from '@/components/Upload/ImgUploadOneC'
import ImgUploadOne from '@/components/Upload/ImgUploadOne'
import registerDialog from './components/registerDialog'
/** 页面组件 end*/

/** 页面接口 start*/
import { listRegionTree } from '@/api/common/area.js'
import { enterpriseRegister, enterpriseBusiness, checkEccUniqueOut } from '@/api/register'
import { listNoPermission } from '@/api/superviseBaseInfo/typeManage/organizationType/index'
// 验证码接口
import { changeCertificate } from '@/api/register'
import { validateorgCreditode } from '@/utils/validate.js'
import { getSysDicts } from '../../api/common/getSysDicts'
/** 页面接口 end*/
export default {
  components: {
    ImgUploadOneC,
    ImgUploadOne,
    registerDialog
  },
  data() {
    return {
      loading: false,
      certId: '',
      active: 1, // 步骤条进度
      supperType: [], // 企业类型
      checkSupperType: '', // 选择的企业的类型
      // 经营范围
      businessData: {
        businessScopeJson: [] // 选择的经营范围的id
      },
      titleList: '', // 企业经营范围标题
      CheckBusinessData: [], // 选择的经营范围二维数组
      // 企业信息
      certificateJson: [], // 证书数据
      cityOptions: [], // 城市数据
      cityNormalizer: {
        value: 'value',
        label: 'label',
        children: 'children'
      },
      // 账号密码信息
      initEnterprise: {},
      natureData: [], // 企业性质
      formData: {
        address: '',
        name: '', // 企业名称
        legalperson: '', // 单位法人
        sysEnterpriseType: '', // 企业类型
        creditCodePic: '', // 信用代码
        currentProvince: '', // 所属地区
        nature: '', // 企业性质
        province: '',
        city: '',
        area: '',
        establishmentTime: '', // 成立日期
        qualificationLevel: '', // 资质等级
        validUntil: '', // 证书有效期
        certificateNum: '', // 证书编号
        isCheck: '1', // 审核方式
        unitCreditCodePicUrl: '', // 营业执照
        certifileList: '', // 固定的证书
        qualificationUrl: '' // 固定的证书id
      },
      certifileList: [],
      // 审核方式
      isCheckList: [
        { value: '0', label: '手动审核' },
        { value: '1', label: '自动审核' }
      ],
      // 企业信息规则
      baseRules: {
        name: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
        sysEnterpriseType: [{ required: true, message: '企业类型不能为空', trigger: 'change' }],
        creditCodePic: [
          { required: true, message: '企业信用代码不能为空', trigger: 'blur' },
          { validator: validateorgCreditode, trigger: 'blur' },
          { validator: this.checkEccUniqueOut, trigger: 'blur' }
        ],
        nature: [{ required: true, message: '企业性质不能为空', trigger: 'change' }],
        province: [{ required: true, message: '地区不能为空', trigger: 'change' }],
        address: [{ required: true, message: '地址不能为空', trigger: 'blur' }],
        legalperson: [{ required: true, message: '单位法人不能为空', trigger: 'blur' }],
        unitCreditCodePicUrl: [{ required: true, message: '营业执照不能为空', trigger: 'change' }],
        certificateNum: [{ required: true, message: '证书编号不能为空', trigger: 'blur' }],
        qualificationLevel: [{ required: true, message: '资质等级不能为空', trigger: 'change' }],
        isCheck: [{ required: true, message: '请选择审核方式' }],
        establishmentTime: [{ required: true, message: '企业成立日期不能为空', trigger: 'blur' }],
        validUntil: [{ required: true, message: '证书资质有效期不能为空', trigger: 'change' }]
      },
      proGrade: [] // 项目等级
    }
  },
  computed: {
  },
  watch: {
    // 监听填写进度
    active(val) {
      if (val === 2 && this.supperType.length === 0) {
        this.getSupperType() // 企业类型
        // store.dispatch('basicInfo/getSysDicts') // 系统字典
        this.getBusiness() // 获取拥有项
        this.getRegionTree() // 地区三级联动
        this.getSysDictsProGrade() // 项目等级
        // 获取企业性质
        this.getDicts('enterprise_nature').then(response => {
          this.natureData = response.data.rows
        })
      }
    }
  },
  mounted() {
    // 图片验证码
    this.$refs.registerDialog.getCode()
  },
  methods: {
    // 获取项目等级
    getSysDictsProGrade() {
      getSysDicts('sys_basicInfo_proGrade').then(res => {
        if (res) {
          this.proGrade = res.data.rows
        } else {
          this.msgError(res.message)
        }
      })
    },
    // 校验企业信用代码是否重复
    async checkEccUniqueOut() {
      const { data } = await checkEccUniqueOut({ creditCodePic: this.formData.creditCodePic })
      if (data === '1') {
        return this.msgError('企业信用代码已存在，请重新输入')
      }
    },
    // 获取证书
    getCertData(data, certId) {
      const cert = this.certificateJson.find(item => item.id === certId)
      if (!cert) return
      cert.detailList.forEach(item => {
        this.$set(item, 'value', '')
      })
      for (const k in data) {
        const item = cert.detailList.find(item => item.fileVal === k)
        if (item) {
          this.$set(item, 'value', data[k])
        }
      }
    },
    // 点击证书图片
    handleId(certId) {
      this.certId = certId
    },
    // 选择企业类型
    async checkCompanyType(typeNum) {
      this.checkSupperType = this.supperType.filter((item) => { return item.typeNum === typeNum })[0].typeNum
      this.formData.tempId = this.supperType.filter((item) => { return item.typeNum === typeNum })[0].tempId
      if (this.formData.tempId === null) {
        this.msgWarning('请为当前选择的企业类型配置套餐!')
        return
      }
      const { data } = await changeCertificate({ typeFlag: '1', typeNum })
      if (data) {
        data.sort((a, b) => {
          a.detailList.sort((c, d) => c.orderNum - d.orderNum)
          return a.orderNum - b.orderNum
        })
        this.certificateJson = data
      }
    },
    /** 企业基本信息 start*/
    // 获取企业类型
    async getSupperType() {
      const query = { typeVal: 1 }
      const { data: { rows }} = await listNoPermission(query)
      this.supperType = rows
    },
    // 营业执照
    getBusinessPic(fileList) {
      this.formData.unitCreditCodePicUrl = fileList[0].fileId
    },
    // 经营范围
    goBusiness() {
      this.$refs.baseInfo.validate((valid) => {
        if (valid) {
          const flag = this.certificateJson.some(item => {
          // 证书附件值
            if (item.appFilePic === undefined) return true
            // 字段值
            return item.detailList.some(val => val.value === undefined || val.value.trim() === '')
          })
          if (flag) {
            this.msgWarning('证书附件和信息不能为空!')
          } else {
            this.active = 3
          }
        }
      })
    },
    // 获取区域树
    async getRegionTree() {
      const { data } = await listRegionTree({ regionCode: '' })
      this.cityOptions = this.deleteChildren(data)
    },
    // 所属区域
    changeCitySelect(regionCode) {
      const [province, city, county] = regionCode
      this.formData.province = province // 省
      this.formData.city = city// 市
      this.formData.area = county // 区/县
      this.formData.foreignCompany = city === '130100' ? '1' : '0'
    },
    /** 企业基本信息 end*/

    /** 企业经营范围 start*/
    // 获取经营范围
    async getBusiness() {
      const { data } = await enterpriseBusiness()
      this.titleList = data
      this.CheckBusinessData = this.titleList.map((item) => {
        return []
      })
    },
    // 固定的资质证书
    getCertifileList(fileList) {
      this.formData.qualificationUrl = fileList[0].fileId
    },
    // 选择经营范围
    handleChange() {
      this.businessData.businessScopeJson = []
      this.CheckBusinessData.forEach(item => {
        item.forEach(businessId => {
          this.businessData.businessScopeJson.push({ businessId })
        })
      })
    },
    // 动态经营范围降维
    flattenDeep(arr1) {
      return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(this.flattenDeep(val)) : acc.concat(val), [])
    },
    // 注册
    async goRegister() {
      this.loading = true
      // if (this.formData.tempId === null && !this.goBusiness()) return
      const { formData, initEnterprise, businessData: { businessScopeJson }, certificateJson, checkSupperType } = this
      const obj = certificateJson.map(cert => {
        const { id, appFilePic, detailList, certificateName } = cert
        const certificateVal = detailList.map(item => {
          const { fieldName, fileVal, value, isRemind } = item
          return { fieldName, fileVal, value, isRemind }
        })
        return { certificateName, certificateId: id, fileId: appFilePic[0].fileId, certificateVal: JSON.stringify(certificateVal) }
      })
      if (checkSupperType !== '03' && checkSupperType !== '04') {
        this.formData.validUntil = ''
        this.formData.certificateNum = ''
        this.formData.certifileList = ''
      }
      try {
        const { code } = await enterpriseRegister({
          ...initEnterprise,
          ...formData,
          businessScopeJson: JSON.stringify(businessScopeJson),
          certificateJson: obj
        })
        if (code === 200) {
          this.msgSuccess('注册成功！')
          this.$router.push('/login')
        }
      } catch {
        this.loading = false
      }
    }

    /** 企业经营范围 end*/
  }
}
</script>
